import { auditCostApi, deleteFeeApi, getListApi, getPageStaticApi, statisticsDataApi, addCostExcelApi } from "@/api/financialManagement/receivable/additionalExpense";
// import CommonHook from "@/hook/commonHook";
import { message, Modal } from "ant-design-vue";
import dayjs from "dayjs";
import { Ref, computed, createVNode } from "vue";
import { ExclamationCircleOutlined } from "@ant-design/icons-vue";
export default function OperationHook(state: {
  searchForm: AdditionalExpense.SearchForm;
  tableData: Ref<AdditionalExpense.ListRows[]>;
  tableRef: Ref<any>;
  dialogOpts: Base.DialogOpts;
  drawerOpts: Base.DrawerOpts;
  loading: Ref<boolean>;
  activeKey: Ref<string>;
  pageStat: Ref<Base.GeneraDataType>;
}) {
  const { searchForm, tableData, drawerOpts, loading, tableRef, dialogOpts, activeKey, pageStat } = state;
  const selectRows = computed<Array<AdditionalExpense.ListRows>>(() => {
    return tableRef.value.xTable.getCheckboxRecords() || [];
  });
  // const { getNoZeroKey } = CommonHook();
  const getData = async () => {
    const params = {
      ...getParams(),
      approvalState: Number(activeKey.value)
    };
    loading.value = true;
    tableData.value = [];
    return getListApi(params)
      .then((res: any) => {
        const { code, data } = res;
        if (code === 200) {
          tableData.value = data.records || [];
          searchForm.beforePageNum = searchForm.pageNum;
          searchForm.total = Number(data.total);
        }
      })
      .finally(() => {
        loading.value = false;
      });
  };
  const getParams = () => {
    const { waybillNums, shortName, customerIdList, customerName, costName, createTime, createByList, depositTime, pageNum, pageSize, beforePageNum, companyIdList } = searchForm;
    const params: any = {
      shortName,
      customerName,
      costName,
      createByList,
      customerIdList,
      beforePageNum,
      depositStartTime: depositTime.length ? dayjs(depositTime[0]).format("YYYY-MM-DD HH:mm:ss") : "",
      depositEndTime: depositTime.length ? dayjs(depositTime[1]).format("YYYY-MM-DD HH:mm:ss") : "",
      createStartTime: createTime.length ? dayjs(createTime[0]).format("YYYY-MM-DD HH:mm:ss") : "",
      createEndTime: createTime.length ? dayjs(createTime[1]).format("YYYY-MM-DD HH:mm:ss") : "",
      pageNum,
      pageSize,
      companyIdList
    };
    if (waybillNums)
      params.waybillNums = waybillNums
        .trim()
        .replace(/,{1,}|，{1,}|\+{1,}|\s{1,}/g, ",")
        .split(",");
    if (searchForm.sort) {
      params.order = searchForm.order;
      params.sort = searchForm.sort;
    }
    return params;
  };
  const pageStateic = () => {
    const params = getParams();
    return getPageStaticApi({ ...params }).then((res: any) => {
      const { code, data } = res;
      if (code === 200) {
        Object.assign(pageStat.value, {
          "0": data[0],
          "1": data[1]
        });
        // activeKey.value = String(getNoZeroKey(pageStat.value, ["0", "1"]));
      }
    });
  };
  const searchHandle = async () => {
    searchForm.pageNum = 1;
    await pageStateic();
    getData();
  };
  const changeTabHandle = () => {
    getData();
  };
  // 审核
  const auditHandle = () => {
    if (!selectRows.value.length) return message.error("请勾选费用!");
    Modal.confirm({
      title: "确认审核勾选的运单费用?",
      icon: createVNode(ExclamationCircleOutlined),
      onOk() {
        auditCostApi({
          ids: selectRows.value.map((t: AdditionalExpense.ListRows) => t.id),
          type: 1
        }).then((res: any) => {
          const { code } = res;
          if (code === 200) {
            message.success("审核成功!");
            searchHandle();
          }
        });
      }
    });
  };
  // 追加费用
  const addFeeHandle = () => {
    dialogOpts.title = `追加费用`;
    dialogOpts.width = "520px";
    dialogOpts.type = 1;
    dialogOpts.component = "AddFee";
    dialogOpts.passData = {};
    dialogOpts.visible = true;
  };

  // 修改追加费用
  const modifyAddFeeHandle = (row: AdditionalExpense.ListRows) => {
    dialogOpts.title = `修改追加费用`;
    dialogOpts.width = "520px";
    dialogOpts.type = 2;
    dialogOpts.component = "AddFee";
    dialogOpts.passData = row;
    dialogOpts.visible = true;
  };
  // 导入追加费用
  const importAddFeeHandle = () => {
    dialogOpts.title = `导入追加费用`;
    dialogOpts.width = "520px";
    dialogOpts.type = 1;
    dialogOpts.component = "ImportAddFee";
    dialogOpts.passData = {};
    dialogOpts.visible = true;
  };
  // 删除费用
  const deleteFeeHandle = () => {
    if (!selectRows.value.length) return message.error("请勾选费用!");
    Modal.confirm({
      title: "是否将勾选的费用删除?",
      icon: createVNode(ExclamationCircleOutlined),
      onOk() {
        deleteFeeApi(selectRows.value.map((t: AdditionalExpense.ListRows) => t.id)).then((res: any) => {
          const { code } = res;
          if (code === 200) {
            message.success("删除成功!");
            searchHandle();
          }
        });
      }
    });
  };
  // 反审核
  const reverseFeeHandle = () => {
    if (!selectRows.value.length) return message.error("请勾选费用!");
    Modal.confirm({
      title: "是否将勾选的费用进行反审核?",
      icon: createVNode(ExclamationCircleOutlined),
      onOk() {
        auditCostApi({
          ids: selectRows.value.map((t: AdditionalExpense.ListRows) => t.id),
          type: 2
        }).then((res: any) => {
          const { code } = res;
          if (code === 200) {
            message.success("撤销成功!");
            searchHandle();
          }
        });
      }
    });
  };
  // 查看删除日志
  const showDeleteLogHandle = () => {
    drawerOpts.title = `删除记录`;
    drawerOpts.width = "1200px";
    drawerOpts.type = 1;
    drawerOpts.component = "DeleteLog";
    drawerOpts.passData = {};
    drawerOpts.visible = true;
  };
  // 获取统计数据
  const getStatisticsDataFn = () => {
    const params: any = {
      ...getParams(),
      approvalState: Number(activeKey.value)
    };
    if (selectRows.value.length) params.list = selectRows.value;
    return statisticsDataApi(params).then((res: any) => {
      const { code, data } = res;
      if (code === 200) {
        dialogOpts.passData = data || {};
      }
    });
  };
  // 查看统计
  const showStatictisHandle = () => {
    dialogOpts.title = "查看统计";
    dialogOpts.width = "900px";
    dialogOpts.component = "DataStatistics";
    dialogOpts.visible = true;
  };
  //导出
  const downloadDataHandle = () => {
    const params = {
      ...getParams(),
      list: selectRows.value.length ? selectRows.value : undefined,
      approvalState: activeKey.value
    };

    return addCostExcelApi(params).then((res: any) => {
      const { code } = res;
      if (code === 200) {
        message.success("创建任务成功，请前往导出中心下载！");
      }
    });
  };
  return {
    searchHandle,
    getData,
    addFeeHandle,
    changeTabHandle,
    deleteFeeHandle,
    reverseFeeHandle,
    showDeleteLogHandle,
    auditHandle,
    importAddFeeHandle,
    getStatisticsDataFn,
    showStatictisHandle,
    downloadDataHandle,
    modifyAddFeeHandle
  };
}
